<template>
  <view class="exam-paper">
    <swiper
      class="exam-swiper"
      :duration="config.swiperDuration"
      :current="examIndex"
      @change="onChange"
    >
      <swiper-item v-for="(item, index) in examData" :key="item.exam_id">
        <!-- 当前页与前后两页渲染卷面试题内容，其他页不渲染以节约资源提升性能 -->
        <exam-paper-item
          v-if="Math.abs(examIndex - index) <= 1"
          :idx="index"
          :cur-item="item"
        ></exam-paper-item>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
import config from '@/uni_modules/sv-exam-plus/config.js'
import ExamPaperItem from './exam-paper-item.vue'
import store from '@/uni_modules/sv-exam-plus/store/index.js'

export default {
  components: {
    ExamPaperItem
  },
  props: {
    // 当前题目
    paper: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      config // 兼容写法，需要先声明否则报错
    }
  },
  // #ifdef VUE2
  model: {
    prop: 'paper',
    event: 'update:paper'
  },
  // #endif
  computed: {
    examData: {
      set(newData) {
        store.commit('updateData', newData)
      },
      get() {
        return store.state.examData
      }
    },
    examIndex: {
      set(newIndex) {
        store.commit('updateIndex', newIndex)
      },
      get() {
        return store.state.examIndex
      }
    },
    curPaper() {
      return store.state.examData[this.examIndex]
    }
  },
  watch: {
    paper: {
      handler(newPaper) {
        store.commit('updateIndex', newPaper?.index || 0)
      },
      immediate: true
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      store.commit('updateIndex', this.paper?.index || 0)
      // 监听开始答题默认进度
      uni.$once('sv-exam-start', (index) => {
        store.commit('updateIndex', index || 0)
      })
    },
    onChange(e) {
      store.commit('updateIndex', e.detail.current)
      this.$emit('update:paper', { data: this.curPaper, index: this.examIndex })
    }
  }
}
</script>

<style lang="scss">
.exam-paper {
  width: 100%;
  height: calc(100% - #{var(--card-header-height)});
  font-size: 16px;

  .exam-swiper {
    height: 100%;
  }
}
</style>
